using B.S.XZYData.Api.Read.Application.Command.Process;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Linq;
using SqlSugar;

namespace B.S.XZYData.Api.Read.Application.Handler.Process
{
    /// <summary>
    /// 工序分页查询处理器
    /// </summary>
    public class QueryProcessHandler : IRequestHandler<QueryProcessCommand, ApiResult<ProcessPageResult>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Process> _processRepo;
        private readonly IBaseRepository<RoleModel> _roleRepo;
        private readonly IBaseRepository<Defective> _defectiveRepo;
        private readonly ILogger<QueryProcessHandler> _logger;

        public QueryProcessHandler(
            IBaseRepository<Domain.ZSHH.Process> processRepo,
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<Defective> defectiveRepo,
            ILogger<QueryProcessHandler> logger)
        {
            _processRepo = processRepo;
            _roleRepo = roleRepo;
            _defectiveRepo = defectiveRepo;
            _logger = logger;
        }

        public async Task<ApiResult<ProcessPageResult>> Handle(QueryProcessCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<ProcessPageResult>();
            try
            {
                // 构建查询条件
                var query = _processRepo.GetAll()
                    .Where(x => !x.IsDeleted);

                // 工序编号模糊查询
                if (!string.IsNullOrEmpty(request.ProcessNumber))
                {
                    query = query.Where(x => x.ProcessNumber.Contains(request.ProcessNumber));
                }

                // 工序名称模糊查询
                if (!string.IsNullOrEmpty(request.ProcessName))
                {
                    query = query.Where(x => x.ProcessName.Contains(request.ProcessName));
                }

                // 报工权限查询
                if (!string.IsNullOrEmpty(request.ReportingPermissions))
                {
                    query = query.Where(x => x.ReportingPermissions.Contains(request.ReportingPermissions));
                }

                // 报工数配比范围查询
                if (request.ReportingRatioStart.HasValue)
                {
                    query = query.Where(x => x.ReportingRatio >= request.ReportingRatioStart.Value);
                }
                if (request.ReportingRatioEnd.HasValue)
                {
                    query = query.Where(x => x.ReportingRatio <= request.ReportingRatioEnd.Value);
                }

                // 不良品项列表查询
                if (!string.IsNullOrEmpty(request.DefectiveItemList))
                {
                    query = query.Where(x => x.DefectiveItemList != null && x.DefectiveItemList.Contains(request.DefectiveItemList));
                }

                // 测试字段1查询
                if (!string.IsNullOrEmpty(request.TestField1))
                {
                    query = query.Where(x => x.TestField1 != null && x.TestField1.Contains(request.TestField1));
                }

                // 测试字段2查询
                if (!string.IsNullOrEmpty(request.TestField2))
                {
                    query = query.Where(x => x.TestField2 != null && x.TestField2.Contains(request.TestField2));
                }

                // 创建时间范围查询
                if (request.CreationTimeStart.HasValue)
                {
                    query = query.Where(x => x.CreatorDate >= request.CreationTimeStart.Value);
                }
                if (request.CreationTimeEnd.HasValue)
                {
                    query = query.Where(x => x.CreatorDate <= request.CreationTimeEnd.Value);
                }

                // 排序处理
                query = ApplySorting(query, request.SortField, request.SortDirection);

                // 获取总记录数
                var totalCount = await query.CountAsync();

                // 分页查询
                var processList = await query
                    .Skip((request.PageNumber - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 转换为DTO并处理数据转换
                var processDtoList = await ConvertToDtoList(processList);

                // 构建分页结果
                var result = new ProcessPageResult
                {
                    TotalCount = totalCount,
                    Data = processDtoList,
                    PageNumber = request.PageNumber,
                    PageSize = request.PageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / request.PageSize)
                };

                res.Data = result;
                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";
                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"查询工序异常：{ex.Message}");
                res.Msg = "查询工序异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }

        /// <summary>
        /// 应用排序
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.Process> ApplySorting(
            ISugarQueryable<Domain.ZSHH.Process> query, 
            string sortField, 
            string sortDirection)
        {
            switch (sortField.ToLower())
            {
                case "processnumber":
                    return sortDirection.ToLower() == "asc" 
                        ? query.OrderBy(x => x.ProcessNumber)
                        : query.OrderByDescending(x => x.ProcessNumber);
                
                case "processname":
                    return sortDirection.ToLower() == "asc" 
                        ? query.OrderBy(x => x.ProcessName)
                        : query.OrderByDescending(x => x.ProcessName);
                
                case "creatordate":
                    return sortDirection.ToLower() == "asc" 
                        ? query.OrderBy(x => x.CreatorDate)
                        : query.OrderByDescending(x => x.CreatorDate);
                
                default:
                    // 默认按Id倒序
                    return query.OrderByDescending(x => x.Id);
            }
        }

        /// <summary>
        /// 转换为DTO列表并处理数据转换
        /// </summary>
        private async Task<List<ProcessDto>> ConvertToDtoList(List<Domain.ZSHH.Process> processList)
        {
            var result = new List<ProcessDto>();

            foreach (var process in processList)
            {
                var dto = new ProcessDto
                {
                    Id = process.Id,
                    ProcessNumber = process.ProcessNumber,
                    ProcessName = process.ProcessName,
                    ReportingPermissions = await ConvertReportingPermissionsToNames(process.ReportingPermissions),
                    ReportingRatio = process.ReportingRatio ?? 1,
                    DefectiveItemList = await ConvertDefectiveItemListToNames(process.DefectiveItemList),
                    TestField1 = process.TestField1,
                    TestField2 = process.TestField2,
                    CreatorDate = process.CreatorDate,
                    Creator = process.Creator,
                    UpdatorDate = process.UpdatorDate,
                    Updator = process.Updator
                };

                result.Add(dto);
            }

            return result;
        }

        /// <summary>
        /// 将报工权限ID转换为角色名称
        /// </summary>
        private async Task<string> ConvertReportingPermissionsToNames(string? reportingPermissions)
        {
            if (string.IsNullOrEmpty(reportingPermissions))
                return string.Empty;

            var permissionIds = reportingPermissions.Split(',', StringSplitOptions.RemoveEmptyEntries);
            var roleNames = new List<string>();

            foreach (var permissionId in permissionIds)
            {
                if (int.TryParse(permissionId.Trim(), out var roleId))
                {
                    if (roleId == 0)
                    {
                        roleNames.Add("所有人");
                    }
                    else
                    {
                        var role = _roleRepo.GetAll()
                            .Where(x => !x.IsDeleted && x.Id == roleId)
                            .ToList()
                            .FirstOrDefault();
                        
                        if (role != null)
                        {
                            roleNames.Add(role.RoleName);
                        }
                    }
                }
            }

            return string.Join(",", roleNames);
        }

        /// <summary>
        /// 将不良品项ID转换为名称描述
        /// </summary>
        private async Task<string> ConvertDefectiveItemListToNames(string? defectiveItemList)
        {
            if (string.IsNullOrEmpty(defectiveItemList))
                return string.Empty;

            var items = defectiveItemList.Split(',', StringSplitOptions.RemoveEmptyEntries);
            var descriptions = new List<string>();

            foreach (var item in items)
            {
                var itemId = item.Trim();
                
                // 尝试解析为数字ID
                if (int.TryParse(itemId, out var defectiveId))
                {
                    var defective = _defectiveRepo.GetAll()
                        .Where(x => !x.IsDeleted && x.Id == defectiveId)
                        .ToList()
                        .FirstOrDefault();

                    if (defective != null)
                    {
                        descriptions.Add($"{defective.DefectiveCode} | {defective.DefectiveName}");
                    }
                    else
                    {
                        descriptions.Add(itemId);
                    }
                }
                else
                {
                    // 如果不是数字ID，尝试按原来的逻辑处理
                    var parts = itemId.Split('|', StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length >= 2)
                    {
                        var code = parts[0].Trim();
                        var description = parts[1].Trim();

                        var defective = _defectiveRepo.GetAll()
                            .Where(x => !x.IsDeleted && x.DefectiveCode == code)
                            .ToList()
                            .FirstOrDefault();

                        if (defective != null)
                        {
                            descriptions.Add($"{defective.DefectiveCode} | {defective.DefectiveName}");
                        }
                        else
                        {
                            descriptions.Add(itemId);
                        }
                    }
                    else
                    {
                        descriptions.Add(itemId);
                    }
                }
            }

            return string.Join(",", descriptions);
        }
    }
} 